package com.cheng.spider.extract.novel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class NovelWriter {

    private static final Logger LOGGER = LoggerFactory.getLogger(NovelWriter.class);

    private static FileWriter NOVEL_WRITER;

    private static boolean inited = false;

    private NovelWriter() {
    }

    public static boolean inited() {
        return inited;
    }

    public static void init(String fileName) {
        if (!inited) {
            synchronized (NovelWriter.class) {
                if (!inited) {
                    try {
                        File file = new File(fileName);
                        if (!file.exists()) {
                            LOGGER.info("目标文件不存在，创建新文件");
                            file.createNewFile();
                        }
                        LOGGER.info("存储文件绝对路径：" + file.getAbsolutePath());
                        NOVEL_WRITER = new FileWriter(file);
                        inited = true;
                    } catch (IOException e) {
                        LOGGER.error("打开文件写入流时出错：" + fileName);
                        e.printStackTrace();
                    }
                    if (NOVEL_WRITER == null) {
                        LOGGER.error("NOVEL_WRITER 为空：" + fileName);
                    }
                }
            }
        }
    }

    public static void write(String line) {
        try {
            NOVEL_WRITER.write(line);
            NOVEL_WRITER.flush();
        } catch (IOException e) {
            LOGGER.error("写入内容至文件时出错");
            e.printStackTrace();
        }
    }

    public static void close() {
        try {
            LOGGER.info("关闭写入流");
            NOVEL_WRITER.close();
        } catch (IOException e) {
            LOGGER.error("关闭写入流时出错!");
            e.printStackTrace();
        }
    }
}
